import React, {Component} from 'react'
import imgSrc from "./1.png"

export default class cart extends Component {
    operate(_id, e) {
        this.props.operate(e.target.getAttribute('data-index'), _id);
    }
    showCartList() {
        return this.props.cartList.map((item, index) => {
            return (
                <tr key={
                        item._id
                    }
                    onClick={
                        (e) => this.operate(item._id, e)
                }>
                    <td>{
                        item._id
                    }</td>
                    <td><img className="table-img"
                            src={imgSrc}
                            alt=""/></td>
                    <td>{
                        item.name
                    }</td>
                    <td>{
                        item.price
                    }</td>
                    <td>
                        <button data-index="-1">-</button>
                        {
                        item.count
                    }
                        <button data-index="1">+</button>
                    </td>
                    <td>{
                        item.count * item.price
                    }</td>
                    <td className="delete">
                        <button data-index='3'>删除</button>
                    </td>
                </tr>
            )
        })
    }
    getSum() {
        let sum = 0;
        this.props.cartList.forEach(item => {
            sum += item.count * item.price
        });
        return sum
    }
    render() {
        return (
            <div className="cart">
                <h1>购物车</h1>
                <table border="1" cellSpacing="0" cellPadding="0" style={{marginBottom:'50px'}}>
                    <thead>
                        <tr>
                            <th>编号</th>
                            <th>图片</th>
                            <th>标题</th>
                            <th>价格</th>
                            <th>数量</th>
                            <th>小计</th>
                            <th>删除</th>
                        </tr>
                    </thead>
                    <tbody>{
                        this.showCartList()
                    }
                        <tr>
                            <td colSpan="7" style={{lineHeight:'50px'}}>
                                总计：{this.getSum()} </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        )
    }
}
